package com.chromatic.competition.service;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chromatic.competition.inteface.UserInitializationService;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.chromatic.competition.R;
import com.chromatic.competition.utils.RetrofitClientUtil;
import com.chromatic.competition.view.notifications.SpeakActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Response;

public class ChatBotTaskService extends AsyncTask<String, Void, String> {
    @SuppressLint("StaticFieldLeak")
    private final SpeakActivity speakActivity;
    public ChatBotTaskService(SpeakActivity activity) {
        speakActivity = activity;
    }
    UserInitializationService userInitializationService = RetrofitClientUtil.getInstance().getApiService();
    @SuppressLint("StaticFieldLeak")

    protected String doInBackground(String... params) {
        LinearLayout chatBox = speakActivity.findViewById(R.id.chat_box);
        int childCount = chatBox.getChildCount();
        List<JsonObject> messagesList = new ArrayList<>();

        for (int i = 0; i < childCount; i++) {
            View child = chatBox.getChildAt(i);
            RelativeLayout messageContainer = child.findViewById(R.id.message_container_self);
            if (messageContainer == null) {
                messageContainer = child.findViewById(R.id.message_container_assistant);
            }
            TextView messageTextView = child.findViewById(R.id.message_content);
            String role = (messageContainer.getGravity() == Gravity.END) ? "user" : "assistant";
            String content = messageTextView.getText().toString().trim();

            JsonObject messageObject = new JsonObject();
            messageObject.addProperty("role", role);
            messageObject.addProperty("content", content);
            messagesList.add(messageObject);
        }
        JsonObject requestData = new JsonObject();
        JsonArray messagesArray = new Gson().toJsonTree(messagesList).getAsJsonArray();
        requestData.addProperty("model", "gpt-3.5-turbo");
        requestData.add("messages", messagesArray);

        Call<Map<String, Object>> response = userInitializationService.sendMessage(requestData);

        try {
            // 执行 API 请求，得到响应体
            Response<Map<String, Object>> apiResponse = response.execute();
            //检查响应是否成功，如果不成功则处理错误
            if (!apiResponse.isSuccessful()) {
                String errorMessage = "请求失败：" + apiResponse.code() + " " + apiResponse.message();
                Snackbar snackbar = Snackbar.make(speakActivity.findViewById(android.R.id.content), errorMessage, Snackbar.LENGTH_LONG);
                snackbar.setAction("重新加载", (View.OnClickListener) view -> {
                    new ChatBotTaskService(speakActivity).execute();
                });
                snackbar.show();
            }
            // 从响应体中获取响应数据
            Map<String, Object> responseData = apiResponse.body();
            if (responseData == null) {
                return null;
            }
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseData.get("choices");
            if (choices == null || choices.isEmpty()) {
                return null;
            }
            Map<String, String> message = (Map<String, String>) choices.get(0).get("message");
            assert message != null;
            return Objects.requireNonNull(message.get("content")).trim();

        } catch (IOException e) {
            // 发生异常时调用 onCancelled() 方法来通知 AsyncTask 被取消
            cancel(true);
        }
        return null;
    }

    protected void onPostExecute(String assistantMessage) {
        if (assistantMessage != null) {
            View assistantMessageView = speakActivity.getLayoutInflater().inflate(R.layout.message_assistant, null);
            TextView assistantMessageContent = assistantMessageView.findViewById(R.id.message_content);
            LinearLayout chatBox = speakActivity.findViewById(R.id.chat_box);
            assistantMessageContent.setText(assistantMessage);
            chatBox.addView(assistantMessageView);
            speakActivity.runOnUiThread(() -> {
                ScrollView chatBox_Scroll = speakActivity.findViewById(R.id.chat_box_scrollview);
                chatBox_Scroll.post(() -> chatBox_Scroll.fullScroll(View.FOCUS_DOWN));
            });
        }
    }

    protected void onCancelled() {
        speakActivity.runOnUiThread(() -> {
            // 显示一个错误提示框
            AlertDialog.Builder builder = new AlertDialog.Builder(speakActivity);
            builder.setTitle("错误");
            builder.setMessage("获取响应失败，请稍后重试。");
            builder.setPositiveButton("确定", null);
            AlertDialog dialog = builder.create();
            dialog.show();

            builder = new AlertDialog.Builder(speakActivity);
            builder.setTitle("请求失败").setMessage("是否重新发送消息？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new ChatBotTaskService(speakActivity).execute();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            dialog = builder.create();
            dialog.show();
        });
    }
}
